#include "MorphologyDialog.h"
#include <sstream>
#include <string>



MorphologyDialog::MorphologyDialog (QWidget *parent)
: AbstractDialog (parent), _pCurAction (new MorphologyAction)
{
  ui.setupUi(this);
  ui.cbOperation->addItem (tr ("Dilation"));
  ui.cbOperation->addItem (tr ("Erosion"));
  ui.cbOperation->addItem (tr ("Open"));
  ui.cbOperation->addItem (tr ("Close"));
}



MorphologyDialog::~MorphologyDialog ()
{

}



void MorphologyDialog::_openEvent ()
{
  _pCurAction = new MorphologyAction;
  __pWork->getDoc ()->openPreview (_pCurAction.cvt< AbstractAction > ());
  _pCurAction->startAction (__pWork);
  structElemTextChanged ();
  _pCurAction->setActionType (ui.cbOperation->currentIndex ());
  //ui.txStructElem->setText ("");
  //operationChanged (0);
}



void MorphologyDialog::_closeEvent (int r)
{
  if (r == QDialog::Accepted)
    _pCurAction->applyAction ();
  else
    _pCurAction->rejectAction ();
  __pWork->getDoc ()->closePreview ();
  emit repaintViewport ();
}



void MorphologyDialog::structElemTextChanged ()
{
  vector< int > numbers;
  QString strStructElem = ui.txStructElem->toPlainText ();

  QStringList rows = strStructElem.split ('\n');
  int rowNum = 0;
  int columnNum = -1;

  for (QStringList::iterator i = rows.begin(); i != rows.end(); ++i)
  {
    if (i->isEmpty ()) continue;
    QStringList aRow = i->split (' ');
    ++rowNum;
    int curColumns = 0;

    for (QStringList::iterator j = aRow.begin(); j != aRow.end(); ++j)
    {
      if (j->isEmpty ()) continue;
      bool isInt = false;
      int number = j->toInt (&isInt);
      if (!isInt)
        return;
      numbers.push_back (number);
      ++curColumns;
    }
    numbers.push_back (-1); // signal for end of a row
    if (columnNum < curColumns) columnNum = curColumns;
  }
  
  if (rowNum == 0 || columnNum == 0)
    return;

  Core< int > structElem (QSize (columnNum, rowNum), 
    QPoint (columnNum / 2, rowNum / 2));
  int index = 0;
  for (int j = 0; j < rowNum; ++j)
  {
    for (int i = 0; i < columnNum; ++i)
    {
      if (numbers[index] != -1)
      {
        structElem (i, j) = numbers[index];
        ++index;
      }
      else // fill zero
      {
        structElem (i, j) = 0;
      }
    }
    if (numbers[index] == -1) ++index; // skip the end-row signal
  }

  _pCurAction->setStructElem (structElem);

  emit repaintViewport ();
}



void MorphologyDialog::operationChanged (int opIndex)
{
  _pCurAction->setActionType (opIndex);
  emit repaintViewport ();
}
